package com.presto.directo.mvvm.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.isInvisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.presto.directo.R
import com.presto.directo.base.BaseActivity
import com.presto.directo.databinding.ActivityBankListBinding
import com.presto.directo.mvvm.adapter.BankListAdapter
import com.presto.directo.mvvm.viewmodel.BankListViewModel
import com.presto.directo.mvvm.viewmodel.getViewModel
import com.presto.directo.utils.Af
import com.presto.directo.utils.track

class BankListActivity : BaseActivity() {

    private val binding by lazy { ActivityBankListBinding.inflate(layoutInflater) }
    private val viewModel: BankListViewModel by lazy { getViewModel() }
    private val bankListAdapter by lazy { BankListAdapter(R.layout.item_bank_list) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Af.show_bank_list_page.track(this)
        binding.rvBankList.layoutManager = LinearLayoutManager(this).apply { orientation = RecyclerView.VERTICAL }
        binding.rvBankList.adapter = bankListAdapter
        viewModel.bankListLiveData.observe(this) {
            bankListAdapter.addData(it)
            binding.slider.isInvisible = bankListAdapter.data.isNullOrEmpty()
        }
        binding.slider.setSideBarLayout { letter ->
            val index = bankListAdapter.data.indexOfFirst {
                try {
                    it.bank_code[0].toString().contentEquals(letter, true)
                } catch (e: Exception) {
                    false
                }
            }
            if (index >= 0) {
                binding.rvBankList.scrollToPosition(index)
                (binding.rvBankList.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(index, 0)
            }
        }
        viewModel.getBankList()
        bankListAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent()
            intent.putExtra("bankCode", bankListAdapter.getItem(position).bank_code)
            intent.putExtra("bankName", bankListAdapter.getItem(position).bank_name)
            setResult(RESULT_OK, intent)
            finish()
        }
    }

    override val rootView: View
        get() = binding.root

}